package com.telecomyt.jwportal.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.telecomyt.jwportal.R;
import com.telecomyt.jwportal.widget.GlideCircleTransform;
import com.telecomyt.jwportal.widget.GlideRoundTransform;

import java.io.File;
import java.math.BigDecimal;


/**
 * Created by WangCheng .
 * on 2018/5/25.
 * Glide特点
 * 使用简单
 * 可配置度高，自适应程度高
 * 支持常见图片格式 Jpg png gif webp
 * 支持多种数据源  网络、本地、资源、Assets 等
 * 高效缓存策略    支持Memory和Disk图片缓存 默认Bitmap格式采用RGB_565内存使用至少减少一半
 * 生命周期集成   根据Activity/Fragment生命周期自动管理请求
 * 高效处理Bitmap  使用Bitmap Pool使Bitmap复用，主动调用recycle回收需要回收的Bitmap，减小系统回收压力
 * 这里默认支持Context，Glide支持Context,Activity,Fragment，FragmentActivity
 */
@SuppressLint("CheckResult")
@SuppressWarnings("unused")
public class GlideUtils {

    /**
     * 默认加载
     */
    public static void load(Context mContext, String path, ImageView mImageView) {
        Glide.with(mContext)
                .load(path)
                .transform(new GlideRoundTransform(mContext,10))
                .placeholder(R.drawable.ic_launcher_background)
                .into(mImageView);
    }

    /**
     * 默认加载
     */
    public static void loadHeader(Context mContext, String path, ImageView mImageView,int width,int height) {
        Glide.with(mContext)
                .load(path)
                .transform(new GlideRoundTransform(mContext,10))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .override(width, height)//宽高统一存为控件大小
                 .into(mImageView);
    }
    /**
     * 默认加载
     */
    public static void loadCircle(Context mContext, String path, ImageView mImageView) {
        Glide.with(mContext)
                .load(path)
                .transform(new GlideCircleTransform())
                .placeholder(R.mipmap.ic_launcher)
                .into(mImageView);
    }
    /**
     * 默认加载1
     */
    public static void loadDefault(Context mContext, String path, ImageView mImageView) {
        Glide.with(mContext)
                .load(path)
                .apply(new RequestOptions()
                        .placeholder(R.drawable.ic_launcher_background)
                        .error(R.drawable.ic_launcher_background))
                .into(mImageView);
    }

    public static RequestOptions getDefaultOptions() {
        RequestOptions options = new RequestOptions();
        options.placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_background)
                .centerCrop();
        return options;
    }

    public static RequestOptions getDefaultNoCenterOptions() {
        RequestOptions options = new RequestOptions();
        options.placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_background);
        return options;
    }

    /**
     * RelativeLayout加载
     */
    public static void load(Context mContext, String path, final RelativeLayout relative) {
        SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                relative.setBackground(resource);
            }
        };
        Glide.with(mContext)
                .load(path)
                .apply(getDefaultOptions())
                .into(simpleTarget);

    }


    /**
     * 设置加载中的图片,和error图片
     */
    @SuppressLint("CheckResult")
    public static void load(Context mContext, String path, ImageView mImageView, int lodingImage, int errorImageView) {
        RequestOptions options = new RequestOptions();
        options.placeholder(lodingImage).error(errorImageView).fitCenter();
        Glide.with(mContext).load(path).apply(options).into(mImageView);
    }

    /**
     * 设置加载中的图片
     *
     * @param lodingImage 加载中展示的图片
     */
    public static void load(Context mContext, String path, ImageView mImageView, int lodingImage) {
        RequestOptions options = new RequestOptions();
        options.placeholder(lodingImage);
//                .error(errorImageView);
        Glide.with(mContext).load(path).apply(options).into(mImageView);
    }

    /**
     * 配置加载
     *
     * @param options 设置加载中,失败参数
     */
    public static void load(Context mContext, String path, ImageView mImageView, RequestOptions options) {
        if (options == null) {
            options = getDefaultOptions();
//            options = new RequestOptions();
//            options.placeholder(R.drawable.no_banner)// 正在加载中的图片
//                    .error(R.drawable.no_banner); // 加载失败的图片
//                    .diskCacheStrategy(DiskCacheStrategy.ALL); // 磁盘缓存策略
        }
        Glide.with(mContext)
                .load(path)
                .apply(options) // 参数
                .into(mImageView);
    }

    public static void loadHomeImage(Context mContext, String path, ImageView mImageView) {
//        RequestOptions options = new RequestOptions();
//        options.placeholder(R.drawable.no_banner).error(R.drawable.no_banner).fitCenter();
        Glide.with(mContext)
                .load(path)
                .apply(getDefaultOptions().fitCenter())
                .into(mImageView);
    }


    //显示圆形图片
    public static void loadRoundImageView(Context mContext, String path, ImageView mImageView, RequestOptions options) {
        if (options == null) {
//            options = getDefaultOptions()
//                    .centerCrop()
//                    .transforms(new CropCircleTransformation(mContext));
//            options.placeholder(R.drawable.no_banner)// 正在加载中的图片
//                    .error(R.drawable.no_banner)// 加载失败的图片
//                    .centerCrop()
//                    .diskCacheStrategy(DiskCacheStrategy.ALL); // 磁盘缓存策略
        }
        Glide.with(mContext)
                .load(path)
                .apply(options)
                .into(mImageView);
    }

    //加载指定大小
    public static void loadImageViewSize(Context mContext, String path, int width, int height, ImageView mImageView, RequestOptions options) {
        if (options == null) {
            options = getDefaultOptions()
//            options.placeholder(R.drawable.no_banner)// 正在加载中的图片
//                    .error(R.drawable.no_banner)// 加载失败的图片
                    .centerCrop()
                    .override(width, height);
//                    .diskCacheStrategy(DiskCacheStrategy.ALL); // 磁盘缓存策略
        }
        Glide.with(mContext).load(path).apply(options).into(mImageView);
    }


    //设置加载中以及加载失败图片并且指定大小
    public static void loadImageViewLodingSize(Context mContext, String path, int width, int height, ImageView mImageView, int lodingImage, int errorImageView) {
        RequestOptions options = new RequestOptions();
        options.placeholder(lodingImage).error(errorImageView)
                .override(width, height);
        Glide.with(mContext).load(path).apply(options).into(mImageView);
    }

    //设置跳过内存缓存
    public static void loadImageViewCache(Context mContext, String path, ImageView mImageView) {
        RequestOptions options = new RequestOptions();
        options.skipMemoryCache(true);
        Glide.with(mContext).load(path).apply(options).into(mImageView);
    }

    //设置下载优先级
    public static void loadImageViewPriority(Context mContext, String path, ImageView mImageView) {
        RequestOptions options = new RequestOptions();
        options.priority(Priority.NORMAL);
        Glide.with(mContext).load(path).apply(options).into(mImageView);
    }

    /**
     * 策略解说：
     * <p>
     * all:缓存源资源和转换后的资源
     * <p>
     * none:不作任何磁盘缓存
     * <p>
     * source:缓存源资源
     * <p>
     * result：缓存转换后的资源
     */
    //设置缓存策略
    public static void loadImageViewDiskCache(Context mContext, String path, ImageView mImageView) {
        RequestOptions options = new RequestOptions();
        options.placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_background)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(mContext).load(path).apply(options).into(mImageView);
    }

    /**
     * 会先加载缩略图
     * 设置缩略图支持
     */
    public static void loadImageViewThumbnail(Context mContext, String path, ImageView mImageView) {
        Glide.with(mContext).load(path).thumbnail(0.1f).into(mImageView);
    }

    /**
     * api提供了比如：centerCrop()、fitCenter()等
     */

    //设置动态转换
    public static void loadImageViewCrop(Context mContext, String path, ImageView mImageView) {
        RequestOptions options = new RequestOptions();
        options.centerCrop();
        Glide.with(mContext).load(path).apply(options).into(mImageView);
    }


    //清理磁盘缓存
    public static void GuideClearDiskCache(Context mContext) {
        //理磁盘缓存 需要在子线程中执行
        Glide.get(mContext).clearDiskCache();
    }

    //清理内存缓存
    public static void GuideClearMemory(Context mContext) {
        //清理内存缓存  可以在UI主线程中进行
        Glide.get(mContext).clearMemory();
    }

    /**
     * 自适应宽度加载图片。保持图片的长宽比例不变，通过修改imageView的高度来完全显示图片。
     */
    public static void loadIntoUseFitWidth(Context context, final String imageUrl, final ImageView imageView) {
        Glide.with(context)
                .load(imageUrl)
                .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_background))
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        if (imageView == null) {
                            return false;
                        }
                        if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                        ViewGroup.LayoutParams params = imageView.getLayoutParams();
                        int vw = imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();
                        float scale = (float) vw / (float) resource.getIntrinsicWidth();
                        int vh = Math.round(resource.getIntrinsicHeight() * scale);
                        params.height = vh + imageView.getPaddingTop() + imageView.getPaddingBottom();
                        imageView.setLayoutParams(params);
                        return false;
                    }
                })
                .into(imageView);
    }
    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen.xml");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 获取当前屏幕截图，包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 获取当前屏幕截图，不包含状态栏
     */
    public static Bitmap snapShotWithoutStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
                - statusBarHeight);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public static String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     */
    private static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除指定目录下的文件，这里用于缓存的删除
     *
     * @param filePath       filePath
     * @param deleteThisPath deleteThisPath
     */
    private void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "B";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    /**
     * @param rv
     */
    public static void handleRecycleView(final Context context, RecyclerView rv) {
        if (context == null || rv == null) {
            return;
        }
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            boolean sIsScrolling;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 查看源码可知State有三种状态：SCROLL_STATE_IDLE（静止）、SCROLL_STATE_DRAGGING（上升）、SCROLL_STATE_SETTLING（下落）
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://空闲状态 滚动静止时才加载图片资源，极大提升流畅度
//                        if (sIsScrolling) {
                        if (context != null && context instanceof Activity && !((Activity) context).isFinishing())
                            Glide.with(context).resumeRequests();
//                        }
//                        sIsScrolling = false;
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                    case RecyclerView.SCROLL_STATE_SETTLING:
//                        sIsScrolling = true;
                        if (context instanceof Activity && !((Activity) context).isFinishing())
                            Glide.with(context).pauseRequests();
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
    }
}
